package ru.spb.hibissscus.http;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.ContentEncodingHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.*;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Master to make the http connection
 */
public class HttpMaster {

    /**
     * Log
     */
    private static final Logger LOG = LoggerFactory.getLogger(HttpMaster.class);

    /**
     * Default apache http client
     */
    private DefaultHttpClient httpClient;

    /**
     * Ugly HttpParams initialization
     * 
     * @return HttpParams
     */
    private HttpParams createHttpParams() {
        HttpParams params = new SyncBasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSocketBufferSize(params, 8192);
        HttpProtocolParams
                .setUserAgent(
                        params,
                        "Chrome/20.0.1132.47 Opera/9.80 (Windows NT 6.1; U; es-ES) "
                                +
                                "Presto/2.9.181 Version/12.00 Mozilla/5.0 (Windows NT 6.1) "
                                +
                                "AppleWebKit/536.5 (KHTML, like Gecko) Safari/536.5");

        return params;
    }

    /**
     * Constructor
     */
    public HttpMaster() {
        this.httpClient = new ContentEncodingHttpClient(createHttpParams());
        this.httpClient.getParams().setParameter(
                CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
    }

    /**
     * Proxy setter
     * 
     * @param proxy
     *            httpProxy
     */
    public void setupProxy(HttpHost proxy) {
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                proxy);
    }

    /**
     * Get BufferedHttpEntity from url
     * 
     * @param url
     *            url for response
     * @return BufferedHttpEntity
     */
    public BufferedHttpEntity getResponseEntity(String url) {
        HttpGet httpget = new HttpGet(url);

        try {
            HttpResponse response = httpClient.execute(httpget);

            HttpEntity entity = response.getEntity();

            return new BufferedHttpEntity(entity);
        } catch (IOException e) {
            LOG.error("{}", e);
            LOG.error("URL: {} request PROBLEM", url);
            return null;
        }
    }
}
